package com.business_clean.app.ext;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.callback.OnDialogCancelListener;
import com.business_clean.app.callback.OnDialogCityIdPickerListener;
import com.business_clean.app.callback.OnDialogCityPickerListener;
import com.business_clean.app.callback.OnDialogConfirmListener;
import com.business_clean.app.callback.OnDialogCreateFinish;
import com.business_clean.app.callback.OnDialogDoubleDateConfirmListener;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.flutter.FlutterManager;
import com.business_clean.app.network.NetUrl;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.weight.dialog.CustomBottomListPopup;
import com.business_clean.app.weight.dialog.CustomCityPickerPopup;
import com.business_clean.app.weight.dialog.CustomContentHighlightPop;
import com.business_clean.app.weight.dialog.CustomDoubleTimePickerPopup;
import com.business_clean.app.weight.dialog.CustomSystemAlertPop;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.data.initconfig.popup.BaseBottomListEntity;
import com.business_clean.data.mode.appupdate.DialogAlertNoticeInfo;
import com.business_clean.data.mode.login.UserInfo;
import com.business_clean.ui.activity.login.LoginActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.impl.ConfirmPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.noober.background.drawable.DrawableCreator;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.business_clean.app.weight.dialog.CustomDialogSlideSingleList;

import org.w3c.dom.Text;

import me.hgj.mvvmhelper.base.KtxKt;
import me.hgj.mvvmhelper.ext.AppExtKt;


/**
 * 全部业务共同使用的类
 */
public class CommonUtils {

    /**
     * 切换环境
     *
     * @param position
     */
    public static void changeEnvironment(int position) {
        switch (position) {
            case 0:
                changeReleaseEnvironment();
                break;
            case 1:
                changeTestEnvironment();
                break;
            case 2:
                changeDevEnvironment();
                break;
        }
        //重启Aap
        restartApp(KtxKt.getAppContext());
    }

    /**
     * 重启App
     *
     * @param context
     */
    public static void restartApp(Context context) {
//        Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
//        if (intent != null) {
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_MUTABLE);
//            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//            if (alarmManager != null) {
//                alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
//            }
//        }
//        // 关闭当前应用
//        if (context instanceof Activity) {
//            ((Activity) context).finish();
//        }

        ActivityForwardUtil.startActivity(LoginActivity.class);
    }

    /**
     * 切换到正式环境
     */
    private static void changeReleaseEnvironment() {
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL_M, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL_M2, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_WEB_URL, NetUrl.WEB_BASE_RELEASE_URL);
        NetUrl.defaultUrl = NetUrl.SERVER_URL_RELEASE;
        NetUrl.WEB_BASE_URL = NetUrl.WEB_BASE_RELEASE_URL;
        FlutterManager.sServerType = FlutterManager.SERVER_TYPE_RELEASE;
    }

    private static void changeTestEnvironment() {
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL, NetUrl.SERVER_URL_TEST);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL_M, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL_M2, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_WEB_URL, NetUrl.WEB_BASE_DEV_URL);
        NetUrl.defaultUrl = NetUrl.SERVER_URL_TEST;
        NetUrl.WEB_BASE_URL = NetUrl.WEB_BASE_DEV_URL;
        FlutterManager.sServerType = FlutterManager.SERVER_TYPE_TEST;

    }


    private static void changeDevEnvironment() {
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL, NetUrl.SERVER_URL_DEV);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL_M, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_URL_M2, NetUrl.SERVER_URL_RELEASE);
        MMKVHelper.putString(ConstantMMVK.ENVIRONMENT_BASE_WEB_URL, NetUrl.WEB_BASE_DEV_URL);
        NetUrl.defaultUrl = NetUrl.SERVER_URL_DEV;
        NetUrl.WEB_BASE_URL = NetUrl.WEB_BASE_DEV_URL;
        FlutterManager.sServerType = FlutterManager.SERVER_TYPE_DEV;

    }

    /**
     * 用户更新全局的数据处理
     *
     * @param userInfo
     */
    public static void updateLocalUserData(UserInfo userInfo) {
        if (userInfo == null) {
            return;
        }
        //项目的
        App.appViewModelInstance.getProjectInfo().setValue(userInfo.getProject());
        App.appViewModelInstance.getUserInfo().setValue(userInfo);
        Constant.ROLE_ID = userInfo.getUser().getRole_id();
        //1管理员 2项目负责人 3人事 4领班 5保洁
        switch (userInfo.getUser().getRole_id()) {
            case "1":
                Constant.ROLE_MANGER = true;
                break;
            case "2":
                Constant.ROLE_PROJECT_OWNER = true;
                break;
            case "3":
                Constant.ROLE_HR = true;
                break;
            case "4":
                Constant.ROLE_LEADER = true;
                break;
            case "5":
                Constant.ROLE_CLEANER = true;
                break;
            case "6":
                Constant.ROLE_REGIONAL_MANAGER = true;
                break;
        }

        //设置图片的配置 是否标记 1 是 2 否
        if ("1".equals(userInfo.getUser().getIs_mark())) {
            Constant.CAMERA_MARK_PHOTO = true;
        } else {
            Constant.CAMERA_MARK_PHOTO = false;
        }
        //设置图片的配置 是否保存水印图片 1 是 2 否
        if ("1".equals(userInfo.getUser().getIs_save_to_phone())) {
            Constant.CAMERA_SAVE_PHOTO_VIDEO = true;
        } else {
            Constant.CAMERA_SAVE_PHOTO_VIDEO = false;
        }
        //设置图片的配置 是否保存原始图片 1 是 2 否
        if ("1".equals(userInfo.getUser().getIs_save_origin_pic())) {
            Constant.CAMERA_SAVE_ORIGINAL_PHOTO = true;
        } else {
            Constant.CAMERA_SAVE_ORIGINAL_PHOTO = false;
        }
    }

    /**
     * 不要频频繁写域名了，直接从这里拿
     *
     * @return
     */
    public static String getWebUrlHost() {
        return MMKVHelper.getString(ConstantMMVK.ENVIRONMENT_BASE_WEB_URL, NetUrl.WEB_BASE_RELEASE_URL);
    }

    /**
     * 显示一般的普通的提示框  有取消和确定 确定按钮高亮 按返回键不关闭探矿
     */
    public static void showGeneralDialogNoDismissOnBackPressed(Context context, String title, String msg, String negationText, String positiveText, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {
        showReal(context, title, msg, negationText, positiveText, true, false, onCancelListener, onConfirmListener);
    }

    /**
     * 显示一般的普通的提示框   有取消和确定  确定按钮不高亮
     */
    public static void showGeneralDialogNoHighLight(Context context, String title, String msg, String negativiText, String positiveText, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {
        showReal(context, title, msg, negativiText, positiveText, false, true, onCancelListener, onConfirmListener);
    }

    /**
     * 显示一般的普通的提示框  有取消和确定 确定按钮高亮
     */
    public static void showGeneralDialog(Context context, String title, String msg, String negativiText, String positiveText, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {
        showReal(context, title, msg, negativiText, positiveText, true, true, onCancelListener, onConfirmListener);
    }

    /**
     * 显示一般的普通的提示框 没有取消按钮，只有确定，确定按钮高亮
     */
    public static void showGeneralDialogNoCancel(Context context, String title, String msg, String positiveText, OnDialogConfirmListener onConfirmListener) {
        showReal(context, title, msg, "", positiveText, true, true, null, onConfirmListener);
    }

    /**
     * 显示一般普通的提示框，内容部分高亮
     */
    public static void showGeneralDialogContentHighlightCancel(Context context, String title, SpannableString spannableString, String positiveText, boolean isHignLight, boolean isHideNegativi, OnDialogConfirmListener onConfirmListener) {
        showRealContentHighlight(context, title, spannableString, "", positiveText, isHignLight, isHideNegativi, true, null, onConfirmListener);
    }

    /**
     * dialog 内容可点击 内容左对齐
     */
    private static void showRealContentHighlight(Context context, String title, SpannableString msg, String negativiText, String positiveText,
                                                 boolean isHignLight, boolean isHideNegativi, boolean dismissOnBackPressed, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {

        CustomContentHighlightPop highlightPop = new CustomContentHighlightPop(context);

        highlightPop.setListener(new OnDialogCreateFinish() {
            @Override
            public void onViewInit() {
                highlightPop.getTvTitle().setText(title);
                highlightPop.getTvContent().setText(msg);
                highlightPop.getTvConfirm().setTextColor(ContextCompat.getColor(context, isHignLight ? R.color.base_primary : R.color.base_primary_text_title));
                highlightPop.getTvCancel().setText(negativiText);
                highlightPop.getTvConfirm().setText(positiveText);
                highlightPop.getTvCancel().setVisibility(isHideNegativi ? View.GONE : View.VISIBLE);
            }
        }, onConfirmListener);

        new XPopup.Builder(context)
                .asCustom(highlightPop)
                .show();
    }


    /**
     * 默认弹窗 确定 取消
     */
    private static void showReal(Context context, String title, String msg, String negationText, String positiveText, boolean isBrightLight, boolean dismissOnBackPressed, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {
        ConfirmPopupView popupView = new XPopup.Builder(context)
                .dismissOnBackPressed(dismissOnBackPressed)
                .dismissOnTouchOutside(true)
                .hasNavigationBar(false)
                .isDestroyOnDismiss(true)
                .popupAnimation(PopupAnimation.NoAnimation)
                .asConfirm(title, msg,
                        negationText, positiveText,
                        onConfirmListener, onCancelListener,
                        TextUtils.isEmpty(negationText),
                        isBrightLight ? R.layout.dialog_base_meterial : R.layout.dialog_base_meterial_no_hign_light);
        popupView.show();
    }


    /**
     * 显示一般的普通的提示框  有取消和确定  内容左对齐
     */
    public static void showGeneralDialogContentLeftGravityWithHighLight(Context context, String title, String msg, String negationText, String positiveText, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {
        ConfirmPopupView popupView = new XPopup.Builder(context)
                .dismissOnBackPressed(true)
                .dismissOnTouchOutside(true)
                .hasNavigationBar(false)
                .isDestroyOnDismiss(true)
                .popupAnimation(PopupAnimation.NoAnimation)
                .asConfirm(title, msg,
                        negationText, positiveText,
                        onConfirmListener, onCancelListener, TextUtils.isEmpty(negationText), R.layout.dialog_base_meterial_content_left_gravity);
        popupView.show();
    }

    /**
     * 显示从底部弹出，带手势拖拽的列表弹窗,带选中效果
     */
    public static void showBottomListNoCheckedWith(Context context, int radius, String title, String[] strings, int checkedPosition, OnSelectListener onSelectListener) {
        new XPopup.Builder(context)
                .isViewMode(true)
                .borderRadius(XPopupUtils.dp2px(context, radius))
                .asBottomList(title, strings, null, checkedPosition, onSelectListener)
                .show();
    }

    /**
     * 显示从底部弹出，带手势拖拽的列表弹窗, 没用选中效果
     */
    public static void showBottomListWith(Context context, int radius, String title, String[] strings, OnSelectListener onSelectListener) {
        new XPopup.Builder(context)
                .isViewMode(true)
                .maxHeight(ScreenUtils.getScreenHeight() / 2)
                .borderRadius(XPopupUtils.dp2px(context, radius))
                .asBottomList(title, strings, onSelectListener)
                .show();
    }

    public static void showCenterListWith(Context context, int radius, String title, String[] strings, OnSelectListener onSelectListener) {
        new XPopup.Builder(context)
                .isViewMode(true)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .borderRadius(XPopupUtils.dp2px(context, radius))
                .asCenterList(title, strings, onSelectListener)
                .show();
    }


    /**
     * 显示从底部弹出，自定义的 Bottom 分主标题跟次标题
     */
    public static void showBottomListCustomWith(Context context, int radius, String title, List<BaseBottomListEntity> datas, OnDialogSelectListener onSelectListener) {
        CustomBottomListPopup popup = new CustomBottomListPopup(context, datas);
        if (!TextUtils.isEmpty(title)) {
            popup.setTitle(title);
        }
        popup.setOnDialogListener(new OnDialogCancelListener() {
            @Override
            public void onCancel() {

            }
        }, onSelectListener);
        new XPopup.Builder(context)
                .isViewMode(true)
                .maxHeight(ScreenUtils.getScreenHeight() / 2)
                .borderRadius(XPopupUtils.dp2px(context, radius))
                .asCustom(popup)
                .show();
    }

    /**
     * 双日期选择-选择日期
     */
    public static void showDialogDoubleTimePickerPopup(Context context, String title, String dialogConfirm, String dialogCancel, int startYear, int endYear, int firstYear, int firstMonth, int firstDay, int secondYear, int secondMonth, int secondDay, OnDialogDoubleDateConfirmListener listener) {
        CustomDoubleTimePickerPopup popup = new CustomDoubleTimePickerPopup(context);
        popup.setListener(new OnDialogCreateFinish() {
            @Override
            public void onViewInit() {
                popup.setCenterText(title);
                popup.setCancelText(dialogCancel);
                popup.setConfirmText(dialogConfirm);
                popup.setDateRange(startYear, endYear, 0, 0, 0);
                popup.setFirstRange(firstYear, firstMonth, firstDay);
                popup.setSecondRange(secondYear, secondMonth, secondDay);
                popup.initWheelDate(); // 必须调用这行代码，不然界面什么都不显示
            }
        }, listener);
        new XPopup.Builder(context)
                .asCustom(popup)
                .show();
    }


    /**
     * 单排列表，传值
     */
    public static void showDialogWheelSingleList(Context context, String content, ArrayList<String> arrList, String inverseText, OnDialogSelectListener onSelectListener) {
        CustomDialogSlideSingleList popup = new CustomDialogSlideSingleList(context);
        popup.setListener(new OnDialogCreateFinish() {
            @Override
            public void onViewInit() {
                popup.setCurrentItem(0);
                popup.setDataList(arrList);
                popup.setCenterText(content);
                popup.setWheelCyclic(false);
                popup.setWheelInverseText(inverseText);
                if (popup.getWheelView() == null) {
                    popup.getWheelView().setLineSpacingMultiplier(2.0F);//设置间距倍数,但是只能在1.0-4.0f之间
                }
            }
        }, () -> {

        }, (position, text) -> {
            if (onSelectListener != null) {
                onSelectListener.onSelect(position, text);
            }
        });
        new XPopup.Builder(context)
                .asCustom(popup)
                .show();
    }


    /**
     * 显示 日历 自定义年月日
     */
    public static void showDialogTimePickerView(Context context, String title, Calendar defDate, int startYear, int endYear, Calendar startDateRang, Calendar endDateRang, CustomTimePickerPopup.Mode mode, OnDialogTimePickerListener listener) {
        Calendar defaultDate = defDate != null ? defDate : Calendar.getInstance();

        CustomTimePickerPopup popup = new CustomTimePickerPopup(context)
                .setTitle(title)
                .setMinutesStep(1)
                .setDefaultDate(defaultDate)
                .setYearRange(startYear, endYear)
                .setDateRang(startDateRang, endDateRang)
                .setMode(mode)
                .setTimePickerListener(listener);

        new XPopup.Builder(context)
                .asCustom(popup)
                .show();
    }

    /**
     * 选择城市
     *
     * @param context
     * @param title
     * @param mode
     * @param curProvice
     * @param curCity
     * @param curArea
     * @param listener
     */
    public static void showDialogCityPickerView(Context context, String title, CustomCityPickerPopup.Mode mode, String curProvice, String curCity, String curArea, OnDialogCityPickerListener listener) {
        CustomCityPickerPopup popup = new CustomCityPickerPopup(context)
                .setMode(mode)
                .setTitle(title)
                .setDefData(curProvice, curCity, curArea)
                .setCityPickerListener(listener);
        new XPopup.Builder(context)
                .asCustom(popup)
                .show();
    }


    /**
     * 选择城市
     *
     * @param context
     * @param title
     * @param mode
     * @param curProvice
     * @param curCity
     * @param curArea
     * @param listener
     */
    public static void showDialogCityPickerView(Context context, String title, CustomCityPickerPopup.Mode mode, String curProvice, String curCity, String curArea, OnDialogCityPickerListener listener, OnDialogCityIdPickerListener cityIdPickerListener) {
        CustomCityPickerPopup popup = new CustomCityPickerPopup(context)
                .setMode(mode)
                .setTitle(title)
                .setDefData(curProvice, curCity, curArea)
                .setCityPickerListener(listener)
                .setCityIdPickerListener(cityIdPickerListener);
        new XPopup.Builder(context)
                .asCustom(popup)
                .show();
    }


    public static void showSystemAlertPop(Context context, DialogAlertNoticeInfo noticeInfo, OnDialogCancelListener onCancelListener, OnDialogConfirmListener onConfirmListener) {
        CustomSystemAlertPop popup = new CustomSystemAlertPop(context);
        popup.setListener(new OnDialogCreateFinish() {
            @Override
            public void onViewInit() {
                popup.setTitle(noticeInfo.getTitle() != null ? noticeInfo.getTitle() : "");
                popup.setSubTitle(noticeInfo.getDescribe() != null ? noticeInfo.getDescribe() : "");
                popup.setContent(noticeInfo.getContent() != null ? noticeInfo.getContent() : "");
                popup.setRightWeight(noticeInfo.getRight_weight());
                if (noticeInfo.getImg_url() != null) {
                    popup.setImgUrl(noticeInfo.getImg_url());
                }
                popup.setLeftButton(noticeInfo.getClose_button() != null ? noticeInfo.getClose_button() : "");
                popup.setRightButton(noticeInfo.getConfirm_button() != null ? noticeInfo.getConfirm_button() : "");
                if (noticeInfo.getSub_title_color() != 0) {
                    popup.setSubTitleColor(noticeInfo.getSub_title_color());
                }
                if (noticeInfo.getContent_bg_color() != 0) {
                    popup.setContentBgColor(noticeInfo.getContent_bg_color());
                }
            }

        }, onCancelListener, onConfirmListener);

        new XPopup.Builder(context)
                .dismissOnBackPressed(noticeInfo.isDismissOnBackPressed())
                .dismissOnTouchOutside(noticeInfo.isDismissOnTouchOutside())
                .asCustom(popup)
                .show();
    }


    /**
     * Xpopup种的图片预览
     */
    public static void showPreviewPhoto(Context context, ImageView imageView, int position, List<String> list) {

    }

    /**
     * 默认选中的 效果 单个View adapter 使用
     */
    public static Drawable getBaseSelectedDrawable(Context context) {
        Drawable drawableSelected = new DrawableCreator.Builder()
                .setCornersRadius(SizeUtils.dp2px(4))
                .setSolidColor(ContextCompat.getColor(context, R.color.base_primary_select))
                .setStrokeColor(ContextCompat.getColor(context, R.color.base_primary))
                .setStrokeWidth(SizeUtils.dp2px(1))
                .build();
        return drawableSelected;
    }

    /**
     * 默认选中的 效果 单个View adapter 使用 不要边框的
     */
    public static Drawable getBaseSelectedNoStrokeDrawable(Context context) {
        Drawable drawableSelected = new DrawableCreator.Builder()
                .setCornersRadius(SizeUtils.dp2px(4))
                .setSolidColor(ContextCompat.getColor(context, R.color.base_primary_select))
                .build();
        return drawableSelected;
    }

    /**
     * 默认选中的 效果 单个View adapter 使用
     */
    public static Drawable getBaseUnSelectedDrawable(Context context) {
        Drawable drawableUnSelected = new DrawableCreator.Builder()
                .setCornersRadius(SizeUtils.dp2px(4))
                .setSolidColor(ContextCompat.getColor(context, R.color.base_primary_un_select))
                .build();
        return drawableUnSelected;
    }


    /**
     * View 的点击切换
     */
    public static Drawable getBaseViewSelectedDrawable(Context context, int dpValue) {
        Drawable drawableSelected = new DrawableCreator.Builder()
                .setCornersRadius(SizeUtils.dp2px(dpValue))
                .setSolidColor(ContextCompat.getColor(context, R.color.base_primary))
                .build();
        return drawableSelected;
    }


    /**
     * 默认选中的 效果 单个View adapter 使用
     */
    public static Drawable getBaseUnSelectedDrawable(Context context, int dpValue, int colorid) {
        Drawable drawableUnSelected = new DrawableCreator.Builder()
                .setCornersRadius(SizeUtils.dp2px(dpValue))
                .setSolidColor(ContextCompat.getColor(context, colorid))
                .build();
        return drawableUnSelected;
    }


    /**
     * View 的点击切换
     */
    public static Drawable getBaseViewSelectedDrawable(Context context, int dpValue, int colorid) {
        Drawable drawableSelected = new DrawableCreator.Builder()
                .setCornersRadius(SizeUtils.dp2px(dpValue))
                .setSolidColor(ContextCompat.getColor(context, colorid))
                .build();
        return drawableSelected;
    }


}


